package com.angenela.lmz.controller;

import com.angenela.lmz.constant.Constant;
import com.angenela.lmz.dto.ObjectDTO;
import com.angenela.lmz.mapper.ImageMapper;
import com.angenela.lmz.mapper.TagMapper;
import com.angenela.lmz.mapper.UserMapper;
import com.angenela.lmz.pojo.Image;
import com.angenela.lmz.pojo.ImageAndUser;
import com.angenela.lmz.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 处理Image相关的请求
 */
@Api(tags = "图片相关接口")
@RestController
@RequestMapping("/image")
public class ImageController {
    private final String IMAGE_FILE_NAME = "file";
    private final String IMAGE_TYPE = ".jpg";

    @Value("${endpoint}")
    private String endpoint;
    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${accessKeySecret}")
    private String accessKeySecret;
    @Value("${bucketName}")
    private String bucketName;
    @Value("${imgUploadPath}")
    private String imgUploadPath;

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TagMapper tagMapper;

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        return uuid;
    }

    public Image initImage(String url, String userId, String tagId) {
        Image image = new Image();
        image.setUserId(Integer.valueOf(userId));
        image.setTagId(Integer.valueOf(tagId));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        image.setCreateTime(format.format(new Date()));
        image.setSrc(url);
        image.setStar(0);
        image.setUserId(Integer.valueOf(userId));
        return image;
    }

    /**
     * 根据tagId随机获取一定数量的图片
     *
     * @param tagId
     * @param count
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping("/rand/{tagId}/{count}")
    @ApiOperation("根据标签id随机获取一定数量的图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tagId", value = "标签的id", required = true),
            @ApiImplicitParam(name = "count", value = "获取的图片数量", required = true)
    })
    public String randImagesByTagId(
            @PathVariable("tagId") String tagId,
            @PathVariable("count") String count
    ) throws JsonProcessingException {
        ObjectDTO dto = new ObjectDTO();
        List<ImageAndUser> iaus = imageMapper.randGetImagesByTagId(Integer.valueOf(tagId), Integer.valueOf(count));
        dto.setData(iaus);
        dto.setCode(Constant.SUCCESS_CODE);
        return objectMapper.writeValueAsString(dto);
    }

    /**
     * 随机获取一定数量的图片
     *
     * @param countStr
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping("/rand/{count}")
    @ApiOperation("随机获取一定数量的图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "count", value = "获取的图片数量", required = true)
    })
    public String randGetImages(@PathVariable("count") String countStr) throws JsonProcessingException {
        Integer count = Integer.valueOf(countStr);
        List<ImageAndUser> images = imageMapper.randGetImages(count);
        return objectMapper.writeValueAsString(images);
    }

    /**
     * 处理根据用户id获取图片的请求
     *
     * @param userId
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping("/user/{userId}")
    @ApiOperation("根据用户id随机获取一定数量的图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户的id", required = true),
    })
    public String getAllImagesByUserId(@PathVariable("userId") String userId) throws JsonProcessingException {
        ObjectDTO dto = new ObjectDTO();
        Integer id = Integer.valueOf(userId);

        User user = userMapper.getUserById(id);
        if (user == null) {
            dto.setCode(Constant.ERROR_CODE);
            dto.setMessage(Constant.USER_NOT_EXIST);
        } else {
            List<ImageAndUser> images = imageMapper.getImageByUserId(id);
            dto.setData(images);
            dto.setCode(Constant.SUCCESS_CODE);
        }

        return objectMapper.writeValueAsString(dto);
    }

    /**
     * 处理图片上传的请求
     *
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("/upload")
    @ApiOperation("上传图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true),
            @ApiImplicitParam(name = "file", value = "上传的图片", required = true),
            @ApiImplicitParam(name = "tagId", value = "上传图片对应的标签id", required = true)
    })
    public String imageUpload(
            @RequestParam("userId") String userId,
            @RequestParam("file") MultipartFile file,
            @RequestParam("tagId") String tagId
    ) throws JsonProcessingException {
        // 返回的json对应的对象
        ObjectDTO dto = new ObjectDTO();

        // 生成UUID用来代替上传文件的文件名
        String filename = getUUID() + IMAGE_TYPE;

        // 以下是上传图片的代码
        InputStream inputStream = null;
        ObsClient obsClient = null;
        try {
            inputStream = file.getInputStream();

            // 创建OBSClient实例。
            obsClient = new ObsClient(accessKeyId, accessKeySecret, endpoint);

            // 上传图片
            PutObjectResult result = obsClient.putObject(bucketName, filename, inputStream);

            // 在数据库中添加对应的信息
            Image image = initImage(result.getObjectUrl(), userId, tagId);
            imageMapper.addImage(image);

            // 设置成功信息
            dto.setData(image);
            dto.setCode(Constant.SUCCESS_CODE);
            dto.setMessage(Constant.SUCCESS_MSG);
        } catch (IOException e) {
            dto.setCode(Constant.SERVICE_ERROR_CODE);
            dto.setMessage(Constant.UPLOAD_FAILURE_MSG);
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            if (obsClient != null) {
                try {
                    obsClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 关闭文件流
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return objectMapper.writeValueAsString(dto);
    }

    @GetMapping("/delete/{imageId}")
    @ApiOperation("上传图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imageId", value = "图片id", required = true),
    })
    public String deleteById(@PathVariable("imageId") Integer id){
        imageMapper.deleteById(id);
        return "200";
    }
}
